<!DOCTYPE html>
<html lang="zh_hans">
    <!-- title -->




<!-- keywords -->




<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" >
    <meta name="author" content="Apm29">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Apm29">
    
    <meta name="keywords" content="hexo,hexo-theme,hexo-blog">
    
    <meta name="description" content="daily post">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>LiveData · 生活中的Design</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href= "/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    <link rel="stylesheet" href= "/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href= "/assets/favicon.ico" />
    <link rel="preload" href="https://unpkg.com/webfontloader@1.6.28/webfontloader.js" as="script" />
    <link rel="preload" href="https://unpkg.com/jquery@3.3.1/dist/jquery.min.js" as="script" />
    <link rel="preload" href="/scripts/main.js" as="script" />
    <link rel="preload" as="font" href="/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<meta name="generator" content="Hexo 5.4.2"></head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/" >生活中的Design.</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">LiveData</a>
            </div>
    </div>
    
    <a class="home-link" href=/>生活中的Design.</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:50vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            LiveData
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class= post-intro-tags >
    
        <a class="post-tag" href="javascript:void(0);" data-tags = "Android">Android</a>
    
</div>
                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">2.5k</span>阅读时长: <span class="post-count reading-time">10 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2019/12/17</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>

  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb() {
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr() {
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function (arr, success, reject) {
    var currReject = function () {
      reject()
      arr.shift()
      if (arr.length)
        async(arr[0], success, currReject)
    }

    async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://unpkg.com/webfontloader@1.6.28/webfontloader.js",
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>
        
        <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <ul>
<li><h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><ul>
<li><code>LiveData</code>是androidx.lifecycle-livedata包下的一个抽象类,实现了一种关联了生命周期的简单观察者模式,主要的功能就是用于视图层与数据间的单向一对多通知,一个<code>LiveData</code>会持有一个可观察的Data对象,一开始是处于<code>NOT_SET</code>状态,当用户通过setValue方法更新后,<code>LiveData</code>会遍历所有的observer(处于Active状态的),通知他们Data的更新.<code>LiveData</code>的行为会在<code>Lifecycle</code>范围内,避免很多Activity Leak和空指针 <strong>本文代码样例都是kotlin,LiveData的源码是java</strong></li>
</ul>
</li>
<li><h1 id="LiveData的使用"><a href="#LiveData的使用" class="headerlink" title="LiveData的使用"></a>LiveData的使用</h1><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//声明一个LiveData</span></span><br><span class="line"> <span class="keyword">val</span> <span class="keyword">data</span>:MutableLiveData&lt;String&gt; = MutableLiveData()</span><br><span class="line"> <span class="comment">//在需要的地方订阅,observer的onChange方法会回调</span></span><br><span class="line"> <span class="keyword">data</span>.observe(lifecycleOwner,observer)</span><br><span class="line"> <span class="comment">//可以和retrofit配合使用</span></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ApiService</span> &#123;</span><br><span class="line">   <span class="meta">@GET(<span class="string">&quot;/api/get&quot;</span>)</span></span><br><span class="line">   <span class="function"><span class="keyword">fun</span> <span class="title">getChannels</span><span class="params">()</span></span>:LiveData&lt;ApiResponse&lt;Page&lt;Media&gt;&gt;&gt;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">//可以和room配合使用</span></span><br><span class="line"> <span class="meta">@Dao</span></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">BorrowModelDao</span> &#123;</span><br><span class="line"></span><br><span class="line">     <span class="meta">@Query(<span class="string">&quot;select * from s_borrow_moel&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">getAllBorrowedItems</span><span class="params">()</span></span>: LiveData&lt;List&lt;BorrowModel&gt;&gt;</span><br><span class="line"></span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">//配合ViewModel保存数据/监听数据更改</span></span><br><span class="line"> <span class="keyword">class</span> <span class="title class_">MyViewModel</span>:<span class="type">ViewModel</span>()&#123;</span><br><span class="line">   <span class="keyword">val</span> <span class="keyword">data</span>:MutableLiveData&lt;String&gt; = MutableLiveData()</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></li>
<li><h1 id="LiveData-Tricks"><a href="#LiveData-Tricks" class="headerlink" title="LiveData Tricks"></a>LiveData Tricks</h1><ul>
<li><p>Transformations.map方法转换LiveData的数据类型<br>比如我们用Retrofit获取了一个User类数据:LiveData<User>,但是我们只想把User.name暴露给外部观察者,那么我们可以这样操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> val userLiveData:MutableLiveData&lt;User&gt; = MutableLiveData()</span><br><span class="line">val userNames:LiveData&lt;String&gt; = Transformations</span><br><span class="line">.map(userLiveData)&#123;</span><br><span class="line">    user -&gt;</span><br><span class="line">    user.name</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Transformations在androidx.lifecycle包下</p>
</blockquote>
</li>
<li><p>MediatorLiveData<br>MediatorLiveData可以同时观察多个LiveData的变化</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//声明</span></span><br><span class="line"><span class="keyword">val</span> mediatorLiveData:MediatorLiveData&lt;String&gt; = MediatorLiveData()</span><br><span class="line"><span class="comment">//其他合适的地方添加source</span></span><br><span class="line">mediatorLiveData.addSource(stringFromNetwork)&#123;</span><br><span class="line">    mediatorLiveData.value = it</span><br><span class="line">&#125;</span><br><span class="line">mediatorLiveData.addSource(stringFromDatabase)&#123;</span><br><span class="line">    mediatorLiveData.value = it</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><h1 id="配合ViewModel使用"><a href="#配合ViewModel使用" class="headerlink" title="配合ViewModel使用"></a>配合ViewModel使用</h1><ul>
<li>我们知道<code>ViewModel</code>可以在一个<code>LifecycleOwner</code>的<code>onCreate</code>到<code>OnDestroy</code>之间保存实例不受到屏幕旋转等ConfigChange的影响<br>所以可以通过<code>Activity/Fragment</code>持有<code>ViewModel</code>,而<code>ViewModel</code>持有各类<code>LiveData</code>,<code>Activity/Fragment</code>注册观察需要的数据,实现数据与UI的同步,而且不会因此发生<code>Activity</code>泄漏,甚至可以用<code>ViewModel</code>来进行<code>Activity/Fragment</code>之间的通讯</li>
</ul>
</li>
<li><h1 id="关于Lifecycle"><a href="#关于Lifecycle" class="headerlink" title="关于Lifecycle"></a>关于Lifecycle</h1><ul>
<li><h2 id="Lifecycle组成"><a href="#Lifecycle组成" class="headerlink" title="Lifecycle组成"></a>Lifecycle组成</h2><ul>
<li><code>LifecycleOwner</code>: <code>Activity/Fragment</code>都是<code>LifecycleOwner</code>(support包下的AppCompatActivity和对应的Fragment),他是androidx.lifecycle:lifecycle-common包下的一个借口,只有getLifecycle()一个方法,返回一个Lifecycle对象</li>
<li><code>Lifecycle</code>: 而这个<code>Lifecycle</code>就是维护生命周期state的主体,默认实现是<code>LifecycleRegistry</code>,这个说起来也挺长的,以后有空再新的文章里仔细说明,反正现在读者只要知道我们常用的<code>AppCompatActivity/Fragment</code>都是可以拿到生命周期Lifecycle的就行了</li>
<li><code>LifecycleObserver</code>: 也是一个接口,不过它一个抽象方法也没有,如果我们需要一个新的自定义的观察<br>者,只要实现这个接口,然后在需要对应生命周期方法回调的方法上添加<br><code>OnLifecycleEvent</code>注解并添加对应注解就好了,<code>LiveData</code>有一个<br><code>LifecycleBoundObserver</code>内部类实现了这个接口,不过继承关系是这样的<br><code>LifecycleObserver</code>  &lt;–<code>GenericLifecycleObserver</code>  &lt;- <code>LifecycleBoundObserver</code>,<br><code>LifecycleBoundObserver</code>会在<code>onStateChange</code>收到回调,不依赖于注解,不过读<br>者现在只要知道在<code>Lifecycle</code>中<code>state</code>发生改变的时候,<code>LifecycleObserver</code>会收<br>到通知(<code>void onStateChanged(LifecycleOwner source, Lifecycle.Event event);</code>)  </li>
</ul>
</li>
</ul>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/5133402-e6115a9f98a3da14.gif?imageMogr2/auto-orient/strip" alt="xianyu.gif"></p>
<ul>
<li><h2 id="LiveData类分析"><a href="#LiveData类分析" class="headerlink" title="LiveData类分析"></a>LiveData类分析</h2><ul>
<li>简单的类结构<br> 有几个内部类,都是ObserverWrapper的子类,用于普通的观察者(带生命周期)的<code>LifecycleBounderObserver</code>,和不带的<code>AlwaysActiveObserver</code>..</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">LiveDate</span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">class</span> <span class="title class_">LifecycleBounderObserver</span> <span class="keyword">extends</span> <span class="title class_">ObserverWrapper</span> <span class="keyword">implements</span> <span class="title class_">GenericLifecycleObserver</span>&#123;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">abstract</span> ObserverWrapper&#123;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">class</span> <span class="title class_">AlwaysActiveObserver</span> <span class="keyword">extends</span> <span class="title class_">ObserverWrapper</span> &#123;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><h2 id="observe入手分析"><a href="#observe入手分析" class="headerlink" title="observe入手分析"></a>observe入手分析</h2><ul>
<li>传入参数: <code>LifecycleOwner</code> , <code>Observer</code>类(简单的回调通知接口)</li>
<li>首先通过<code>LifecycleOwner</code>获取<code>Lifecycle</code>,判断时候是<code>DESTROYED</code>状态,是的话直接return<br>将<code>Observer</code>和<code>LifecycleOwner</code>包装为<code>LifecycleBoundObserver</code>对象</li>
<li>LiveData维护了一个<code>SafeIterableMap&lt;Observer&lt;? super T&gt;, ObserverWrapper&gt;</code> 对象mObservers,保存了Observer和对应的Wrapper,存入LifecycleBoundObserver对象后判断是否已存在并且是否对应当前LifecycleOwner,做出相应的处理,当mObservers中没有时,直接给LifecycleOwner的Lifecycle注册该LifecycleBoundObserver</li>
<li>所以说实际上是我们传入的LifecycleOwner保存的Lifecycle注册了一个观察者,LifecycleBoundObserver会在state 等于 DESTROYED的时候移除该观察者,在其他状态的时候调用activeStateChange()方法</li>
<li>先比较当前mActive和新active,赋值给<code>mActive</code>,然后通过LiveData类的mActivieCount是否为0来判断是不是完全没有通知过,如果是进入非active状态mActiveCount就-1,否则+1,原先未active现在active了,调用<code>onActive</code>方法,新的<code>mActivieCount == 0</code>并且 新active的状态为false就调用<code>onInactive</code>方法,然后判断<code>mActive</code>,true则会调用dispatchValue方法,基本上mActivieCount只会有0 -&gt; 1 ,1 -&gt; 0两个状态变化,所以<code>onActive</code>是LiveData观察者数量从无到有时回调,<code>onInactive</code>反之<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">   <span class="keyword">private</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">ObserverWrapper</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> Observer&lt;? <span class="built_in">super</span> T&gt; mObserver;</span><br><span class="line">    <span class="type">boolean</span> mActive;</span><br><span class="line">    <span class="type">int</span> <span class="variable">mLastVersion</span> <span class="operator">=</span> START_VERSION;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">activeStateChanged</span><span class="params">(<span class="type">boolean</span> newActive)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (newActive == mActive) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// immediately set active state, so we&#x27;d never dispatch anything to inactive</span></span><br><span class="line">        <span class="comment">// owner</span></span><br><span class="line">        mActive = newActive;</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">wasInactive</span> <span class="operator">=</span> LiveData.<span class="built_in">this</span>.mActiveCount == <span class="number">0</span>;</span><br><span class="line">        LiveData.<span class="built_in">this</span>.mActiveCount += mActive ? <span class="number">1</span> : -<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (wasInactive &amp;&amp; mActive) &#123;</span><br><span class="line">            onActive();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (LiveData.<span class="built_in">this</span>.mActiveCount == <span class="number">0</span> &amp;&amp; !mActive) &#123;</span><br><span class="line">            onInactive();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (mActive) &#123;</span><br><span class="line">            dispatchingValue(<span class="built_in">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>上面罗里吧嗦一大推读者可能一脸懵逼,反正结论就是,LiveData状态由没有观察者到有观察者会走<code>onActive</code>方法,反之会走<code>onInactive</code>方法,不管原先状态如何,只要新状态是活跃就会走<code>dispatchValue</code></li>
<li><code>onInactive/onActive</code> 是<code>LiveData</code>里两个open protected的方法,只在MediatorLiveData里有实现,我还没有仔细研究MediatorLiveData,大家可以去看看源码</li>
<li>所以LifecycleBoundObserver新状态为活跃时,会调用外部类<code>LiveData</code>的<code>dispatchValue</code>方法,传入的参数为<code>ObserverWrapper</code>,也就是LifecycleBoundObserver的父类(<code>LifecycleBoundObserver</code>继承了<code>ObserverWrapper</code>,实现了<code>GenericLifecycleObserver</code>),在这要注意下内部类(非静态)是可以拿到外部类实例的,LiveData.this.XXX,忘记的同学复习下,我是好久没用java,突然看到有点懵逼..<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//传入参数是Observer,有的话就分发给它,为null就对所有Observers分发数据</span></span><br><span class="line"> <span class="keyword">void</span> <span class="title function_">dispatchingValue</span><span class="params">(<span class="meta">@Nullable</span> ObserverWrapper initiator)</span> &#123;</span><br><span class="line">   <span class="comment">//如果正在分发数据,就标记为分发无效,分发中的会因此跳出循环</span></span><br><span class="line">    <span class="keyword">if</span> (mDispatchingValue) &#123;</span><br><span class="line">      <span class="comment">//标记为分发无效</span></span><br><span class="line">        mDispatchInvalidated = <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//标记为分发中</span></span><br><span class="line">    mDispatchingValue = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        mDispatchInvalidated = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (initiator != <span class="literal">null</span>) &#123;</span><br><span class="line">            considerNotify(initiator);</span><br><span class="line">            initiator = <span class="literal">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">for</span> (Iterator&lt;Map.Entry&lt;Observer&lt;? <span class="built_in">super</span> T&gt;, ObserverWrapper&gt;&gt; iterator =</span><br><span class="line">                    mObservers.iteratorWithAdditions(); iterator.hasNext(); ) &#123;</span><br><span class="line">                 <span class="comment">//尝试分发</span></span><br><span class="line">                considerNotify(iterator.next().getValue());</span><br><span class="line">                <span class="comment">//标记为无效时会跳出循环,在while循环中等待一次mDispatchInvalidated再次变为true时再次进入for循环</span></span><br><span class="line">                <span class="keyword">if</span> (mDispatchInvalidated) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//没有被标记无效时while循环就执行一次完事,否则会再次执行</span></span><br><span class="line">    &#125; <span class="keyword">while</span> (mDispatchInvalidated);</span><br><span class="line">    mDispatchingValue = <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><code>LiveData</code>中的<code>mDispatchingValue/mDispatchInvalidated</code>在此处保证不会重复分发或者分发旧的value,当<code>setValue</code>分发调用<code>dispatchValue(null)</code>时会遍历所有的Observer分发新值,否则只分发给传入的<code>ObserverWrapper</code>,这里说明下:<code>LiveData</code>维护了<code>mDispatchingValue/mDispatchInvalidated</code>,而Observer可能会有多个,都持有LiveData对象(因为是内部类),所以等待的observer对应的<code>LiveData</code>会获得<code>mDispatchInvalidated = true</code>,中断进行中的分发,让旧数据不再分发</li>
<li><code>considerNotify</code>: 第一步检查<code>ObserverWrapper</code>是否<code>mActive</code>,第二步检查<code>shouldBeActive()</code>,第三步检查<code>ObserverWrapper</code>的版本<code>observer.mLastVersion &gt;= mVersion</code>,最后才通知更新,调用Observer的onChange方法</li>
<li>ObserverWrapper中的mLastVersion /和LiveData的mVersion用来防止再入活跃状态后重复分发</li>
<li><code>ObserverWrapper</code>中的<code>mActive</code>用来控制该观察者是否需要分发(<code>activeStateChanged(boolean)</code>方法的作用下)</li>
</ul>
</li>
<li><h2 id="considerNotify方法"><a href="#considerNotify方法" class="headerlink" title="considerNotify方法"></a>considerNotify方法</h2><p>先上代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">  <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">considerNotify</span><span class="params">(ObserverWrapper observer)</span> &#123;</span><br><span class="line">       <span class="keyword">if</span> (!observer.mActive) &#123;</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">// Check latest state b4 dispatch. Maybe it changed state but we didn&#x27;t get the event yet.</span></span><br><span class="line">       <span class="comment">//</span></span><br><span class="line">       <span class="comment">// we still first check observer.active to keep it as the entrance for events. So even if</span></span><br><span class="line">       <span class="comment">// the observer moved to an active state, if we&#x27;ve not received that event, we better not</span></span><br><span class="line">       <span class="comment">// notify for a more predictable notification order.</span></span><br><span class="line">       <span class="keyword">if</span> (!observer.shouldBeActive()) &#123;</span><br><span class="line">           observer.activeStateChanged(<span class="literal">false</span>);</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">if</span> (observer.mLastVersion &gt;= mVersion) &#123;</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       observer.mLastVersion = mVersion;</span><br><span class="line">       <span class="comment">//noinspection unchecked</span></span><br><span class="line">       observer.mObserver.onChanged((T) mData);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">  ```  </span><br><span class="line">  很简单的逻辑,就是</span><br><span class="line">    <span class="number">1.</span> 第一步判断是否active,这个mActive属性在几种情况下会为<span class="literal">true</span>  </span><br><span class="line">      a. Observer是通过observeForever注册的  </span><br><span class="line">      b. Observer的shouldBeActive返回<span class="literal">true</span></span><br><span class="line">            我们看看方法代码,只有绑定的Lifecycle的State大于STARTED才会为<span class="literal">true</span></span><br><span class="line">```java</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="type">boolean</span> <span class="title function_">shouldBeActive</span><span class="params">()</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);</span><br><span class="line">            &#125;</span><br></pre></td></tr></table></figure>
<p>  mActive会在生命周期变化时会被多次检查</p>
<ol start="2">
<li>第二步再次检查<code>shouldBeActive()</code>状态</li>
<li>第三步检查<code>mLastVersion</code>和<code>mVersion</code><br> 这个version是在setValue时被+1的,检查一下防止重复分发,完成后修改lastVersion然后回调<code>onChange(T)</code></li>
</ol>
</li>
<li><h2 id="setValue-postValue方法的分析"><a href="#setValue-postValue方法的分析" class="headerlink" title="setValue/postValue方法的分析"></a>setValue/postValue方法的分析</h2><p>  按惯例先看看代码,postValue的代码也好理解,只是给赋值操作加了一个锁,并把setValue放到主线程执行,使多个postValue只有最后一个的value生效  </p>
  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">Runnable</span> <span class="variable">mPostValueRunnable</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        Object newValue;</span><br><span class="line">        <span class="keyword">synchronized</span> (mDataLock) &#123;</span><br><span class="line">            newValue = mPendingData;</span><br><span class="line">            mPendingData = NOT_SET;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//noinspection unchecked</span></span><br><span class="line">        setValue((T) newValue);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"> <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">postValue</span><span class="params">(T value)</span> &#123;</span><br><span class="line">    <span class="type">boolean</span> postTask;</span><br><span class="line">    <span class="keyword">synchronized</span> (mDataLock) &#123;</span><br><span class="line">        postTask = mPendingData == NOT_SET;</span><br><span class="line">        mPendingData = value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!postTask) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@MainThread</span></span><br><span class="line"> <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">setValue</span><span class="params">(T value)</span> &#123;</span><br><span class="line">     assertMainThread(<span class="string">&quot;setValue&quot;</span>);</span><br><span class="line">     mVersion++;</span><br><span class="line">     mData = value;</span><br><span class="line">     dispatchingValue(<span class="literal">null</span>);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>  想象一下如果两个线程<code>T-A</code>,<code>T-B</code> 里都执行了postValue传入不同的值A,B,先会在方法内的mDataLock锁住的代码块竞争执行,比如A先执行,<code>mPendingData</code>先被赋值为A,<code>postTask</code> =&gt; true,然后赋值为B,也就是说第一次的赋值才会通过同步块之后的if判断,执行分发runnable,线程<code>T-B</code>只是修改了<code>mPendingValue</code>的值</p>
<p>  然后会有一个主线程上的同步代码块(也是同一个锁),将新值执行<code>setValue</code>,<code>mPendingValue</code>重设为初始值,也就是说取得值实际上是后一个线程的B,后面分发完成重设为<code>NOT_SET</code>,后面的PostValue又进入原来的逻辑了</p>
<blockquote>
<p>postValue的注释也很清楚了:  If you called this method multiple times before a main thread executed a posted task, only<br>the last value would be dispatched.</p>
</blockquote>
</li>
<li><h2 id="基本流程"><a href="#基本流程" class="headerlink" title="基本流程"></a>基本流程</h2><ul>
<li>observe() -&gt; 新建Observer -&gt; Observer的StateChange -&gt; dispatchValue -&gt; considerNotify  </li>
<li>setValue/postValue -&gt; dispatchValue -&gt; considerNotify</li>
</ul>
</li>
<li><h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>LiveData的结构是比较简单的,使用时注意不要多次注册观察者,一般如果在Activity中使用,就在OnCreate方法注册,Activity被关闭或回收后观察者会自动解除订阅,所以不会发生泄漏,我们也可以自己继承LiveData做更多的定制来实现自己的业务逻辑,配合Tranformations工具类和MediatorLiveData可以实现很多比较复杂的逻辑</p>
</li>
</ul>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="https://apm29.github.io">Apm29</a>
            <p>原文链接：<a href="https://apm29.github.io/2019/12/17/LiveData/">https://apm29.github.io/2019/12/17/LiveData/</a>
            <p>发表日期：<a href="https://apm29.github.io/2019/12/17/LiveData/">December 17th 2019, 6:13:22 am</a>
            <p>更新日期：<a href="https://apm29.github.io/2019/12/17/LiveData/">December 18th 2019, 4:57:49 pm</a>
            <p>版权声明：本文采用<a rel="license noopener" target="_blank" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href= "/2019/12/18/NPM%E8%AE%BE%E7%BD%AERegistry/" title= "NPM设置Registry">
                    <div class="nextTitle">NPM设置Registry</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href= "/2019/12/13/AndroidDevMetrics/" title= "AndroidDevMetrics">
                    <div class="prevTitle">AndroidDevMetrics</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

<!-- City版安装代码已完成 -->
    
    
    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:yjw999wow@gmail.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
            
                <a href="//github.com/apm29" class="iconfont-archer github" target="_blank" title=github></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <div style="text-align: center">
        <img src="">
        <a href="https://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">浙ICP备20011000号-1</a>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
    
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>

    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:50vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">简介</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#LiveData%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">LiveData的使用</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#LiveData-Tricks"><span class="toc-number">3.</span> <span class="toc-text">LiveData Tricks</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%85%8D%E5%90%88ViewModel%E4%BD%BF%E7%94%A8"><span class="toc-number">4.</span> <span class="toc-text">配合ViewModel使用</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%B3%E4%BA%8ELifecycle"><span class="toc-number">5.</span> <span class="toc-text">关于Lifecycle</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Lifecycle%E7%BB%84%E6%88%90"><span class="toc-number">5.1.</span> <span class="toc-text">Lifecycle组成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#LiveData%E7%B1%BB%E5%88%86%E6%9E%90"><span class="toc-number">5.2.</span> <span class="toc-text">LiveData类分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#observe%E5%85%A5%E6%89%8B%E5%88%86%E6%9E%90"><span class="toc-number">5.3.</span> <span class="toc-text">observe入手分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#considerNotify%E6%96%B9%E6%B3%95"><span class="toc-number">5.4.</span> <span class="toc-text">considerNotify方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#setValue-postValue%E6%96%B9%E6%B3%95%E7%9A%84%E5%88%86%E6%9E%90"><span class="toc-number">5.5.</span> <span class="toc-text">setValue&#x2F;postValue方法的分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%B5%81%E7%A8%8B"><span class="toc-number">5.6.</span> <span class="toc-text">基本流程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 44
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2022 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/06</span><a class="archive-post-title" href= "/2022/07/06/%E4%BD%BF%E7%94%A8KeepAlive%E5%8A%A8%E6%80%81%E7%BC%93%E5%AD%98%E6%A0%87%E7%AD%BE%E9%A1%B5/" >使用KeepAlive动态缓存标签页</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/05</span><a class="archive-post-title" href= "/2022/07/05/SheetJS%20--%20%E5%89%8D%E7%AB%AF(%E6%B5%8F%E8%A7%88%E5%99%A8)%E5%AF%BC%E5%87%BAExcel%E6%96%87%E4%BB%B6/" >SheetJS -- 前端(浏览器)导出Excel文件</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/22</span><a class="archive-post-title" href= "/2022/06/22/%E9%92%89%E9%92%89H5%E5%BA%94%E7%94%A8%E8%B8%A9%E5%9D%91(1)/" >钉钉H5应用踩坑(1)</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/20</span><a class="archive-post-title" href= "/2022/06/20/%E4%BD%BF%E7%94%A8-vue-composition-api/" >使用@vue/composition-api</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/06</span><a class="archive-post-title" href= "/2022/06/06/Python%E6%B8%85%E9%99%A4NodeModules%E6%96%87%E4%BB%B6%E5%A4%B9%E8%84%9A%E6%9C%AC/" >Python清除NodeModules文件夹脚本</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/06</span><a class="archive-post-title" href= "/2022/06/06/%E5%AF%B9%E6%9C%80%E8%BF%91%E5%86%99%E7%9A%84Android%E5%BA%94%E7%94%A8%E7%9A%84%E6%80%BB%E7%BB%93(1)/" >对最近写的Android应用的总结(1)</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/31</span><a class="archive-post-title" href= "/2022/05/31/Vite-Plugin-Pages%E4%B8%8EKeep-Alive/" >Vite-Plugin-Pages与Keep-Alive</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/27</span><a class="archive-post-title" href= "/2022/05/27/VSCode%E9%85%8D%E7%BD%AE%E4%B8%8E%E6%8F%92%E4%BB%B6(Vue%E5%BC%80%E5%8F%91)/" >VSCode配置与插件（Vue开发）</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/19</span><a class="archive-post-title" href= "/2022/01/19/%E9%9D%99%E6%80%81%E7%BD%91%E7%AB%99%E7%94%9F%E6%88%90%E5%99%A8-Gatsby-%E5%AD%A6%E4%B9%A0/" >静态网站生成器 Gatsby 学习</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2021 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/21</span><a class="archive-post-title" href= "/2021/12/21/Kotlin%E5%8D%8F%E7%A8%8B%E7%9B%B8%E5%85%B3/" >Kotlin协程相关</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/09</span><a class="archive-post-title" href= "/2021/08/09/%E5%88%9D%E8%AF%86Ktorm/" >初识Ktorm</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/05</span><a class="archive-post-title" href= "/2021/08/05/NUXTJS%E7%9A%84%E5%A4%9A%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE/" >NUXTJS的多环境配置</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/05</span><a class="archive-post-title" href= "/2021/08/05/NuxtJS%E9%9D%9E%E6%A0%B9%E7%9B%AE%E5%BD%95%E4%B8%8B%E9%83%A8%E7%BD%B2/" >NuxtJS非根目录下部署</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/24</span><a class="archive-post-title" href= "/2021/07/24/%E4%BD%BF%E7%94%A8vue-sfc-rollup%E5%88%9B%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84NPM%E5%BA%93/" >使用vue-sfc-rollup创建自己的NPM库</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/19</span><a class="archive-post-title" href= "/2021/07/19/Certbot%E7%94%9F%E6%88%90Https%E8%AF%81%E4%B9%A6/" >Certbot生成Https证书</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/19</span><a class="archive-post-title" href= "/2021/07/19/Ubuntu%E4%B8%ADMysql5-0%E9%87%8D%E6%96%B0%E5%AE%89%E8%A3%85%E4%B8%8E%E5%88%9D%E5%A7%8B%E5%8C%96/" >Ubuntu中Mysql5.0重新安装与初始化</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">10/28</span><a class="archive-post-title" href= "/2020/10/28/JetPack-Navigation%E4%B8%ADFragment%E7%9A%84%E8%BF%94%E5%9B%9E%E9%94%AE%E6%8B%A6%E6%88%AA/" >JetPack-Navigation中Fragment的返回键拦截</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/07</span><a class="archive-post-title" href= "/2020/07/07/Flutter%E5%9B%BD%E9%99%85%E5%8C%96flutter-intl/" >Flutter国际化flutter_intl</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/18</span><a class="archive-post-title" href= "/2020/06/18/Vue%E9%A1%B9%E7%9B%AE%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1%E5%AE%9E%E8%B7%B5%EF%BC%88%E5%AE%9E%E7%8E%B0%E5%8A%A8%E6%80%81%E6%9D%83%E9%99%90%EF%BC%89/" >Vue项目动态路由实践（实现动态权限）</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/29</span><a class="archive-post-title" href= "/2020/05/29/%E7%94%A8%E5%88%86%E6%B2%BB%E6%80%9D%E6%83%B3%E9%9D%9E%E9%80%92%E5%BD%92%E8%8E%B7%E5%8F%96N%E4%B8%AA%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0%E7%9A%84%E7%BB%84%E5%90%88/" >用分治思想非递归获取N个数组元素的组合</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/23</span><a class="archive-post-title" href= "/2020/03/23/TravisCi-Gradle%E9%83%A8%E7%BD%B2SpringBoot%E9%A1%B9%E7%9B%AE%E5%88%B0aliyun-ECS/" >TravisCi/Gradle部署SpringBoot项目到aliyun ECS</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/07</span><a class="archive-post-title" href= "/2020/01/07/Linux-OSX-%E5%91%BD%E4%BB%A4/" >Linux/OSX 命令</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/23</span><a class="archive-post-title" href= "/2019/12/23/%E7%94%A8Flutter%E9%87%8D%E6%9E%84%E5%BA%94%E7%94%A8/" >用Flutter重构应用</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/20</span><a class="archive-post-title" href= "/2019/12/20/Docker%E7%AC%94%E8%AE%B0/" >Docker笔记</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href= "/2019/12/19/Hexo/" >Hexo</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href= "/2019/12/19/Android-Text-measure-draw/" >Android Text measure/draw</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href= "/2019/12/19/Flutter-WebView-%E9%94%AE%E7%9B%98%E9%97%AE%E9%A2%98/" >Flutter WebView 键盘问题</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href= "/2019/12/19/Git-Submodule-%E5%AD%90%E6%A8%A1%E5%9D%97/" >Git Submodule(子模块)</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/18</span><a class="archive-post-title" href= "/2019/12/18/Android-Webview%E8%AE%BE%E7%BD%AECookie/" >Android Webview设置Cookie</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/18</span><a class="archive-post-title" href= "/2019/12/18/NPM%E8%AE%BE%E7%BD%AERegistry/" >NPM设置Registry</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/17</span><a class="archive-post-title" href= "/2019/12/17/LiveData/" >LiveData</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/13</span><a class="archive-post-title" href= "/2019/12/13/AndroidDevMetrics/" >AndroidDevMetrics</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/CustomPainter/" >CustomPaint</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/Dart%E5%AD%A6%E4%B9%A0/" >Dart 语法</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/Databinding%20in%20kotlin/" >DataBinding in kotlin</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/Gradle%E5%AD%A6%E4%B9%A0/" >Gradle与Groovy</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/JetpackSetup/" >Jetpack</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/PDFViewerInAndroid/" >PDFViewer on Android</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/Navigation/" >Navigation初探</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/RxCache/" >RxCache</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/RxLifecycle%E5%AD%A6%E4%B9%A0/" >RxLifecycle</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/Spring/" >SpringFrameWork</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/TextView%E4%B8%AD%E6%98%BE%E7%A4%BAHtml%E5%86%85%E5%AE%B9/" >在TextView中显示Html格式的文字</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href= "/2019/12/11/flutter/" >Flutter</a>
        </li>
    
    </div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
        <span class="sidebar-tag-name" data-tags="Android"><span class="iconfont-archer">&#xe606;</span>Android</span>
    
        <span class="sidebar-tag-name" data-tags="JetPack"><span class="iconfont-archer">&#xe606;</span>JetPack</span>
    
        <span class="sidebar-tag-name" data-tags="Tools"><span class="iconfont-archer">&#xe606;</span>Tools</span>
    
        <span class="sidebar-tag-name" data-tags="Linux"><span class="iconfont-archer">&#xe606;</span>Linux</span>
    
        <span class="sidebar-tag-name" data-tags="Flutter"><span class="iconfont-archer">&#xe606;</span>Flutter</span>
    
        <span class="sidebar-tag-name" data-tags="Dart"><span class="iconfont-archer">&#xe606;</span>Dart</span>
    
        <span class="sidebar-tag-name" data-tags="Kotlin"><span class="iconfont-archer">&#xe606;</span>Kotlin</span>
    
        <span class="sidebar-tag-name" data-tags="DataBinding"><span class="iconfont-archer">&#xe606;</span>DataBinding</span>
    
        <span class="sidebar-tag-name" data-tags="Docker"><span class="iconfont-archer">&#xe606;</span>Docker</span>
    
        <span class="sidebar-tag-name" data-tags="Git"><span class="iconfont-archer">&#xe606;</span>Git</span>
    
        <span class="sidebar-tag-name" data-tags="Gradle"><span class="iconfont-archer">&#xe606;</span>Gradle</span>
    
        <span class="sidebar-tag-name" data-tags="Groovy"><span class="iconfont-archer">&#xe606;</span>Groovy</span>
    
        <span class="sidebar-tag-name" data-tags="NPM"><span class="iconfont-archer">&#xe606;</span>NPM</span>
    
        <span class="sidebar-tag-name" data-tags="travisci"><span class="iconfont-archer">&#xe606;</span>travisci</span>
    
        <span class="sidebar-tag-name" data-tags="Fragment"><span class="iconfont-archer">&#xe606;</span>Fragment</span>
    
        <span class="sidebar-tag-name" data-tags="Coroutines"><span class="iconfont-archer">&#xe606;</span>Coroutines</span>
    
        <span class="sidebar-tag-name" data-tags="Shell"><span class="iconfont-archer">&#xe606;</span>Shell</span>
    
        <span class="sidebar-tag-name" data-tags="前端"><span class="iconfont-archer">&#xe606;</span>前端</span>
    
        <span class="sidebar-tag-name" data-tags="nuxtjs"><span class="iconfont-archer">&#xe606;</span>nuxtjs</span>
    
        <span class="sidebar-tag-name" data-tags="Python"><span class="iconfont-archer">&#xe606;</span>Python</span>
    
        <span class="sidebar-tag-name" data-tags="SheetJS"><span class="iconfont-archer">&#xe606;</span>SheetJS</span>
    
        <span class="sidebar-tag-name" data-tags="Spring"><span class="iconfont-archer">&#xe606;</span>Spring</span>
    
        <span class="sidebar-tag-name" data-tags="Springboot"><span class="iconfont-archer">&#xe606;</span>Springboot</span>
    
        <span class="sidebar-tag-name" data-tags="TravisCI"><span class="iconfont-archer">&#xe606;</span>TravisCI</span>
    
        <span class="sidebar-tag-name" data-tags="MySQL"><span class="iconfont-archer">&#xe606;</span>MySQL</span>
    
        <span class="sidebar-tag-name" data-tags="Vue"><span class="iconfont-archer">&#xe606;</span>Vue</span>
    
        <span class="sidebar-tag-name" data-tags="Vite"><span class="iconfont-archer">&#xe606;</span>Vite</span>
    
        <span class="sidebar-tag-name" data-tags="ORM"><span class="iconfont-archer">&#xe606;</span>ORM</span>
    
        <span class="sidebar-tag-name" data-tags="算法"><span class="iconfont-archer">&#xe606;</span>算法</span>
    
        <span class="sidebar-tag-name" data-tags="javascript"><span class="iconfont-archer">&#xe606;</span>javascript</span>
    
        <span class="sidebar-tag-name" data-tags="SSG"><span class="iconfont-archer">&#xe606;</span>SSG</span>
    
        <span class="sidebar-tag-name" data-tags="SEO"><span class="iconfont-archer">&#xe606;</span>SEO</span>
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br/>
    1、请确保node版本大于6.2<br/>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br/>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br/>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
        <span class="sidebar-category-name" data-categories="笔记"><span class="iconfont-archer">&#xe60a;</span>笔记</span>
    
        <span class="sidebar-category-name" data-categories="Git"><span class="iconfont-archer">&#xe60a;</span>Git</span>
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/",
        author: "Apm29"
    }
</script>
    <!-- CDN failover -->
    <script src="https://unpkg.com/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/scripts/share.js" async></script>    
     
    </body>
</html>


